package ui.activity.partner;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Bean.AllyBean;
import base.LazyFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import event.NetErrorEvent;
import event.SearchAllyEvent;
import rx.functions.Action1;
import ui.activity.partner.biz.PartnerBiz;
import ui.activity.partner.component.DaggerPartnerComponent;
import ui.activity.partner.contract.PartnerContract;
import ui.activity.partner.module.PartnerModule;
import ui.activity.partner.presenter.PartnerPresenter;
import ui.adapter.PartnerAdapter;
import util.StringUtils;

/**
 * Created by chenjian on 19/3/11.
 * <p>
 * 未实名合伙人
 */

public class UnRealNameFra extends LazyFragment implements PartnerContract.View {


    @Inject
    PartnerPresenter presenter;
    @Inject
    PartnerBiz biz;


    @BindView(R.id.pull_refresh_rv)
    RecyclerViewFinal rv;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.fragment1_ally_image)
    SimpleDraweeView userImage;
    @BindView(R.id.fragment1_ally_name)
    TextView userName;
    @BindView(R.id.level)
    ImageView level;
    @BindView(R.id.fragment_ally_txt)
    TextView allyTxt;
    @BindView(R.id.fragment_ally_arrow)
    ImageView allyArrow;
    @BindView(R.id.fragment1_ally_linear)
    LinearLayout allyLinear;
    @BindView(R.id.fragment1_ally_num)
    TextView allyNum;

    PartnerAdapter adp;
    private SharedPreferences sp;

    private boolean isPrepared;// 界面否
    private boolean isALeady = true;

    private String mSearchKey = "";
    private static final int SORT_DEFAULT = 0;
    private static final int SORT_ALLY_NUMBER = 1;
    private static final int SORT_MONTH_AMOUNT = 2;
    private static final int SORT_MONTH_ACTIVATE = 3;

    private int mSortType = SORT_DEFAULT;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_real, container, false);
        ButterKnife.bind(this, view);
        DaggerPartnerComponent.builder().partnerModule(new PartnerModule(this)).build().inject(this);
        presenter.setBiz(biz);
        sp = getActivity().getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setItemAnimator(new DefaultItemAnimator());
//        rv.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);

        rv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
            }
        });

        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mSearchKey="";
                presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 0, mSortType, mSearchKey);
            }
        });
        isPrepared = true;
        RxView.clicks(allyLinear)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

//                        showSortPopup();
                    }
                });
        return view;
    }

    @Override
    protected void lazyLoad() {
        if (isPrepared && isVisible && isALeady) {
            // TODO 在这里处理逻辑
            ptr.autoRefresh(true);
            isALeady = false;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        biz.onDestory();
        ButterKnife.bind(getActivity()).unbind();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSearchAllyEvent(SearchAllyEvent event) {
        if (getUserVisibleHint()) {
            mSearchKey = StringUtils.isEmpty(event.input) ? "" : event.input;
            presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 0, mSortType, mSearchKey);
        }
    }


    @Override
    public void upDateUI(AllyBean.DataBean bean) {
        userName.setText(bean.getName() + "");
        userImage.setImageURI(Uri.parse(bean.getHeadImg()));
        switch (bean.getLevelAmount()) {
            case 1:
                level.setBackgroundResource(R.mipmap.r1);
                break;
            case 2:
                level.setBackgroundResource(R.mipmap.r2);
                break;
            case 3:
                level.setBackgroundResource(R.mipmap.r3);
                break;
            case 4:
                level.setBackgroundResource(R.mipmap.r4);
                break;
            case 5:
                level.setBackgroundResource(R.mipmap.r5);
                break;
            case 6:
                level.setBackgroundResource(R.mipmap.r6);
                break;
            case 7:
                level.setBackgroundResource(R.mipmap.r7);
                break;
            case 8:
                level.setBackgroundResource(R.mipmap.r8);
                break;
            case 9:
                level.setBackgroundResource(R.mipmap.r9);
                break;
            case 10:
                level.setBackgroundResource(R.mipmap.r10);
                break;
            case 11:
                level.setBackgroundResource(R.mipmap.r11);
                break;
            case 12:
                level.setBackgroundResource(R.mipmap.r12);
                break;
            default:
                level.setBackgroundResource(R.mipmap.r1);
                break;

        }
        allyNum.setText("合伙人 共" + bean.getItems().size() + "人");
        if (adp == null) {
            adp = new PartnerAdapter(getActivity(), bean.getItems(), mSortType + "", false);
            rv.setAdapter(adp);
        } else {
            adp.setSearchtype(mSortType + "");
            if (bean.getItems().size() == 0) {
                adp.getData().clear();
            } else {
                adp.setDatas(bean.getItems());
            }
            adp.notifyDataSetChanged();
        }
    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }

    @Override
    public void loadMoreComplete() {
        rv.onLoadMoreComplete();
    }

    @Override
    public void hasLoadMore(boolean b) {
        rv.setHasLoadMore(b);
    }


    private void showSortPopup() {
        allyTxt.setTextColor(getResources().getColor(R.color.colorBlue));
        allyArrow.setImageResource(R.drawable.arrow_blue);

        PopupWindow popup = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setFocusable(true);
        popup.setOutsideTouchable(true);
        popup.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_share_bottom_white));

        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popup_ally_sort_type, null);
        popup.setContentView(inflate);
        View sortDefault = inflate.findViewById(R.id.sort_default);
        View sortAllyNumber = inflate.findViewById(R.id.sort_ally_number);
        View sortMonthAmount = inflate.findViewById(R.id.sort_month_amount);
        View sortMonthActivate = inflate.findViewById(R.id.sort_month_activate);
        sortDefault.setVisibility(mSortType == SORT_DEFAULT ? View.GONE : View.VISIBLE);
        sortAllyNumber.setVisibility(mSortType == SORT_ALLY_NUMBER ? View.GONE : View.VISIBLE);
        sortMonthAmount.setVisibility(mSortType == SORT_MONTH_AMOUNT ? View.GONE : View.VISIBLE);
        sortMonthActivate.setVisibility(mSortType == SORT_MONTH_ACTIVATE ? View.GONE : View.VISIBLE);

        sortDefault.setOnClickListener(v -> {
            allyTxt.setText("默认排序");
            mSortType = SORT_DEFAULT;
            presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 1, mSortType, mSearchKey);
            popup.dismiss();
        });
        sortAllyNumber.setOnClickListener(v -> {
            allyTxt.setText("合伙人规模从高到低");
            mSortType = SORT_ALLY_NUMBER;
            presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 1, mSortType, mSearchKey);
            popup.dismiss();
        });
        sortMonthAmount.setOnClickListener(v -> {
            allyTxt.setText("本月交易额从高到低");
            mSortType = SORT_MONTH_AMOUNT;
            presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 1, mSortType, mSearchKey);
            popup.dismiss();
        });
        sortMonthActivate.setOnClickListener(v -> {
            allyTxt.setText("本月合伙人激活商户从多到少");
            mSortType = SORT_MONTH_ACTIVATE;
            presenter.getPartnerList(true, Integer.parseInt(sp.getString("id", "0")), 1, mSortType, mSearchKey);
            popup.dismiss();
        });

        popup.setOnDismissListener(() -> {
            allyTxt.setTextColor(getResources().getColor(R.color.tc_666666));
            allyArrow.setImageResource(R.drawable.arrow);
        });

        popup.showAsDropDown(allyLinear);
    }

}
